﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using System.Xml;

namespace Beyondsoft.Tuanju.DataManager.DealProviders
{
    //<data>
    //    <deal>
    //        <website>美团网</website> 
    //        <city_name>北京</city_name> 
    //        <city_id>beijing</city_id> 
    //        <city_url>http://bj.meituan.com</city_url> 
    //        <deal_id>677983</deal_id> 
    //        <deal_title>仅售168元！价值398元的东方之道住宿1晚，节假通用</deal_title> 
    //        <deal_rank>0</deal_rank> 
    //        <deal_url>http://bj.meituan.com/deal/677983.html</deal_url> 
    //        <deal_wap_url>http://m.meituan.com/beijing/deal/677983.html</deal_wap_url> 
    //        <deal_img>http://p1.meituan.net/275.168/deal/201205/15/0516_0515141255.jpg</deal_img> 
    //        <deal_cate_id>209</deal_cate_id> 
    //        <deal_cate>酒店旅游</deal_cate> 
    //        <deal_subcate_id>105</deal_subcate_id> 
    //        <deal_subcate>特色酒店</deal_subcate> 
    //        <deal_desc>仅售168元！价值398元的东方之道住宿1晚（豪华单人房/豪华双人房2选1），美团券可叠加使用，节假日通用。</deal_desc> 
    //        <value>398</value> 
    //        <price>168</price> 
    //        <rebate>4.2</rebate> 
    //        <sales_min>1</sales_min> 
    //        <sales_num>573</sales_num> 
    //        <sold_out>no</sold_out> 
    //        <is_post>no</is_post> 
    //        <start_time>1337097600</start_time> 
    //        <end_time>1340121599</end_time> 
    //        <coupon_start_time>1337097600</coupon_start_time> 
    //        <coupon_end_time>1341071999</coupon_end_time>
    //        <deal_tips>
    //            <![CDATA[ 有效期：2012.5.16 至 2012.6.30; 营业时间：24小时; 请至少提前3天致电67057766/67017766预约; 每房最多2名成人入住; 1.5米及以下儿童可免费入住; 每房每次最多可使用3张美团券; 不可同时享受店内其它优惠;]]> 
    //        </deal_tips>
    //        <deal_wow>
    //            <![CDATA[ ]]> 
    //        </deal_wow>
    //        <deal_range>天坛</deal_range> 
    //        <deal_address>崇文区天坛东路13号（马路对面天坛体育中心内即是）</deal_address> 
    //        <deal_lng>116.420351</deal_lng> 
    //        <deal_lat>39.880231</deal_lat> 
    //        <deal_name>东方之道住宿</deal_name> 
    //        <deal_seller>东方之道</deal_seller> 
    //        <deal_phones>010-67017766</deal_phones> 
    //    </deal>
    //    <shops>
    //        <shop>
    //            <shop_name>东方之道</shop_name> 
    //            <shop_dpid>0</shop_dpid> 
    //            <shop_tel>010-67017766</shop_tel> 
    //            <shop_addr>崇文区天坛东路13号（马路对面天坛体育中心内即是）</shop_addr> 
    //            <shop_area>天坛</shop_area> 
    //            <shop_long>116.420351</shop_long> 
    //            <shop_lat>39.880231</shop_lat> 
    //            <shop_trafficinfo>
    //                <![CDATA[ 乘25/36/39/208/525/610/614/685/686/723/827/829/957/958路至天坛体育场站下车南行约100米即是]]> 
    //            </shop_trafficinfo>
    //        </shop>
    //    </shops>
    //</data>


    public class MeiTuan : DealProvider
    {
        private const string url = "http://www.meituan.com/api/v2/{0}/deals";

        protected override string Name
        {
            get { return "meituan"; }
        }

        protected override string ApiAddress
        {
            get { return url; }
        }

        protected override async Task<IEnumerable<Deal>> FetchDeals(City city)
        {
            int index = 0;

            string destUrl = string.Format(url, city.CityNamePY);

            List<Deal> deals = new List<Deal>();

            Uri uri = new Uri(destUrl);

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.Async = true;

            XmlReader reader = XmlReader.Create(destUrl, settings);

            while (await reader.ReadAsync())
            {
                ++index;

                if (reader.ReadToFollowing("deal"))
                {
                    string nodeXml = await reader.ReadOuterXmlAsync();
                    deals.Add(await Parse(nodeXml));
                }

                if (index > FetchCount)
                {
                    break;
                }
            }

            return deals;
        }

        private async Task<Deal> Parse(string xml)
        {
            double value = 0;

            XmlDocument xdoc = new XmlDocument();
            xdoc.LoadXml(xml);

            var nodes = xdoc.ChildNodes;

            Deal deal = new Deal();

            foreach (var node in nodes)
            {
                deal.Website = node.SelectSingleNode("website").InnerText;
                deal.Gid = node.SelectSingleNode("deal_id").InnerText;
                deal.Title = node.SelectSingleNode("deal_title").InnerText;

                string category = node.SelectSingleNode("deal_cate").InnerText;
                deal.Category = await this.ConvertFrom(category);

                deal.Description = node.SelectSingleNode("deal_desc").InnerText;
                deal.Details = node.SelectSingleNode("deal_tips").InnerText;
                deal.Price = double.TryParse(node.SelectSingleNode("price").InnerText, out value) ? value : 0;
                deal.Value = double.TryParse(node.SelectSingleNode("value").InnerText, out value) ? value : 0;
                deal.Bought = int.Parse(node.SelectSingleNode("sales_num").InnerText);
                deal.Image = node.SelectSingleNode("deal_img").InnerText;
                deal.StartTime = long.Parse(node.SelectSingleNode("start_time").InnerText).ToDateTime();
                deal.EndTime = long.Parse(node.SelectSingleNode("end_time").InnerText).ToDateTime();

                deal.Discount = deal.Value == 0 ? 0 : Math.Ceiling(deal.Price / deal.Value * 100);
                deal.UriLink = node.SelectSingleNode("deal_url").InnerText;
                deal.ExpireTime = (deal.EndTime - DateTime.Today).Days;
            }

            return deal;
        }
    }
}
